package com.ai.sevice.config;

import com.ai.common.enums.ConfigModuleEnum;
import com.ai.common.utils.ConfigUtil;
import com.ai.common.utils.TraceContext;
import com.ai.dao.entity.PublicConfig;
import com.ai.dao.entity.ai.AiUser;
import com.ai.repository.PublicConfigRepository;
import com.ai.repository.ai.AiUserRepository;
import com.ai.sevice.config.request.AddOrUpdateConfigRequest;
import com.ai.sevice.config.request.DeleteConfigRequest;
import com.ai.sevice.config.request.GetConfigListRequest;
import com.ai.sevice.config.request.GetConfigRequest;
import com.ai.sevice.config.response.*;
import com.ai.sevice.config.response.dto.*;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author ：shengwenyang
 * @date ：Created in 2023/4/23 17:13
 * @description：
 * @version:
 */
@Slf4j
@Service
public class ConfigService {

    @Autowired
    private PublicConfigRepository publicConfigRepository;
    @Autowired
    private AiUserRepository aiUserRepository;

    //////////////////////////////////配置接口///////////////////////////////////////////////////////////////////////////////////////////
    /**
     * 更新或新增配置
     * @param module
     * @param key
     * @param value
     * @return
     */
        public void addOrUpdate(String module,String key,String value) {
            AddOrUpdateConfigRequest request = new AddOrUpdateConfigRequest();
            request.setModule(module);
            request.setKey(key);
            request.setValue(value);
            addOrUpdate(request);
        }

        public AddOrUpdateConfigResponse addOrUpdate(AddOrUpdateConfigRequest request) {
        AddOrUpdateConfigResponse response = new AddOrUpdateConfigResponse();
        try {
            if (StringUtils.isBlank(request.getKey())){
                response.setCode(1);
                response.setMsg("配置key不能为空");
                return response;
            }
            if (request.getValue() == null){
                request.setValue("");
            }
            PublicConfig config = publicConfigRepository.getPublicConfig(request.getModule(),request.getKey());
            int result;
            if (config != null){
                config.setValue(request.getValue());
                result = publicConfigRepository.updateByPrimaryKeySelective(config);
            }else{
                PublicConfig publicConfig = new PublicConfig();
                publicConfig.setModule(request.getModule());
                publicConfig.setConfigKey(request.getKey());
                publicConfig.setValue(request.getValue());
                result = publicConfigRepository.insertSelective(publicConfig);
            }
            if (result <= 0){
                response.setCode(1);
                response.setMsg("配置失败");
            }
            //更新配置缓存
            ConfigUtil.getInstance().addOrUpdateConfig(request.getModule(),request.getKey(),request.getValue());
        }catch (Exception e){
            response.setCode(1);
            response.setMsg("配置异常");
            log.error(e.getMessage(),e);
        }
        return response;
    }

    /**
     * 获取配置
     * @param request
     * @return
     */
    public GetConfigResponse get(GetConfigRequest request) {
        GetConfigResponse response = new GetConfigResponse();
        PublicConfig publicConfig = publicConfigRepository.getPublicConfig(request.getModule(), request.getKey());
        if (publicConfig != null) {
            response.setValue(publicConfig.getValue());
        }
        return response;
    }

    /**
     * 获取配置
     * @param module
     * @param key
     * @return
     */
    public String getValue(String module,String key) {
        if (StringUtils.isBlank(module) || StringUtils.isBlank(key)){
            return null;
        }
        PublicConfig publicConfig = publicConfigRepository.getPublicConfig(module, key);
        if (publicConfig != null) {
            return publicConfig.getValue();
        }
        return null;
    }

    /**
     * 获取配置模块列表
     * @return
     */
    public GetModuleListResponse getModuleList() {
        GetModuleListResponse response = new GetModuleListResponse();
        List<String> moduleList = publicConfigRepository.getModuleList();
        response.setModuleList(moduleList);
        return response;
    }

    /**
     * 删除配置
     * @param request
     * @return
     */
    public DeleteConfigResponse delete(DeleteConfigRequest request) {
        DeleteConfigResponse response = new DeleteConfigResponse();
        PublicConfig config = publicConfigRepository.getPublicConfig(request.getModule(),request.getKey());
        if (config == null){
            response.setCode(1);
            response.setMsg("配置不存在");
            return response;
        }
        config.setIsDelete(1);
        int update = publicConfigRepository.updateByPrimaryKeySelective(config);
        if (update <= 0){
            response.setCode(1);
            response.setMsg("删除配置失败");
            return response;
        }
        //删除配置缓存
        ConfigUtil.getInstance().deleteConfig(request.getModule(),request.getKey());
        return response;
    }

    /**
     * 获取所有配置
     * @param request
     * @return
     */
    public GetConfigListResponse getConfigList(GetConfigListRequest request) {
        GetConfigListResponse response = new GetConfigListResponse();
        if (request.getIsCache() != null && request.getIsCache()){
            ConcurrentHashMap<String, ConcurrentHashMap<String, String>> configModuleMap = ConfigUtil.getInstance().getConfigModuleMap();
            setConfigListResponse(request.getModule(), response, configModuleMap);
            return response;
        }else{
            ConcurrentHashMap<String, ConcurrentHashMap<String, String>> configModuleMap = getPublicConfigList(request.getModule());
            setConfigListResponse(request.getModule(), response, configModuleMap);
        }
        return response;
    }

    /**
     * 配置初始化
     */
    public void initConfig(){
        ConcurrentHashMap<String, ConcurrentHashMap<String, String>> configModuleMap = getPublicConfigList(null);
        if (configModuleMap == null){
            configModuleMap = new ConcurrentHashMap<>();
        }
        ConfigUtil.getInstance().resetConfig(configModuleMap);
        //-------------------同步所有的optionType---------------------------------------
        ConcurrentHashMap<String,String> optionTypeMap = new ConcurrentHashMap<>();
        String cardList = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.aiCard.getModule(), "cardList");
        if (StringUtils.isNotBlank(cardList)){
            List<AiCardCategoryDto> cardCategoryList = JSON.parseArray(cardList,AiCardCategoryDto.class);
            if (CollectionUtils.isEmpty(cardCategoryList)){
                return ;
            }
            for (AiCardCategoryDto aiCardCategoryDto : cardCategoryList){
                List<AiCardDto> aiCardDtoList = aiCardCategoryDto.getCardList();
                if (CollectionUtils.isEmpty(aiCardDtoList)){
                    continue;
                }
                for (AiCardDto aiCardDto : aiCardDtoList){
                    optionTypeMap.put(aiCardDto.getOptionType(),aiCardDto.getTitle());
                }
            }
        }
        ConfigUtil.getInstance().resetOptionTypeMap(optionTypeMap);
    }

    //获取配置列表
    private ConcurrentHashMap<String, ConcurrentHashMap<String, String>> getPublicConfigList(String module) {
        List<PublicConfig> publicConfigList = publicConfigRepository.getPublicConfigList(module);
        if (CollectionUtils.isEmpty(publicConfigList)){
            return null;
        }
        ConcurrentHashMap<String, ConcurrentHashMap<String, String>> configModuleMap = new ConcurrentHashMap<>();
        for (PublicConfig publicConfig : publicConfigList){
            ConcurrentHashMap<String, String> configMap = configModuleMap.get(publicConfig.getModule());
            if (configMap != null){
                if (publicConfig.getConfigKey() != null && publicConfig.getValue() != null) {
                    configMap.put(publicConfig.getConfigKey(), publicConfig.getValue());
                }
            }else{
                configMap = new ConcurrentHashMap<>();
                if (publicConfig.getConfigKey() != null && publicConfig.getValue() != null) {
                    configMap.put(publicConfig.getConfigKey(), publicConfig.getValue());
                }
                configModuleMap.put(publicConfig.getModule(),configMap);
            }
        }
        return configModuleMap;
    }

    //配置列表响应数据
    private void setConfigListResponse(String requestModule, GetConfigListResponse response, ConcurrentHashMap<String, ConcurrentHashMap<String, String>> configModuleMap) {
        if (configModuleMap == null || configModuleMap.size() == 0){
            return;
        }
        List<ConfigModuleDto> moduleList = new ArrayList<>();
        for(Map.Entry<String,ConcurrentHashMap<String, String>> configModule : configModuleMap.entrySet()){
            String module = configModule.getKey();
            if (requestModule != null && !requestModule.equals(module)){
                continue;
            }
            ConcurrentHashMap<String, String> configMap = configModule.getValue();
            if (configMap != null){
                ConfigModuleDto configModuleDto = new ConfigModuleDto();
                configModuleDto.setModule(module);
                List<ConfigDto> configList = new ArrayList<>();
                for(Map.Entry<String,String> entry : configMap.entrySet()){
                    ConfigDto configDto = new ConfigDto();
                    configDto.setKey(entry.getKey());
                    configDto.setValue(entry.getValue());
                    configList.add(configDto);
                }
                configModuleDto.setConfigList(configList);
                moduleList.add(configModuleDto);
            }
        }
        response.setModuleList(moduleList);
    }

    //////////////////////////////业务接口///////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * 获取卡片列表
     * @return
     */
    public GetAiCardListResponse getAiCardList(String uid) {
        GetAiCardListResponse response = new GetAiCardListResponse();
        if (StringUtils.isBlank(uid)){
            response.setCode(1);
            response.setMsg("uid不存在");
            return response;
        }

//        boolean showCard = ConfigUtil.getInstance().isShowCard(uid);
//        if (!showCard){
//            return response;
//        }

        //无权限卡片
        Map<String,String> noAccessCardMap = new HashMap<>();
        String privateCardListStr = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.aiCard.getModule(), "privateCardList");
        if (StringUtils.isNotBlank(privateCardListStr)){
            List<String> privateCardList = Arrays.asList(privateCardListStr.split(","));
            AiUser aiUser = aiUserRepository.getUserByUid(uid);
            if (aiUser == null){
                response.setCode(2);
                response.setMsg("用户不存在");
                return response;
            }
            //获取用户有权限的卡片
            String cardListStr = aiUser.getCardList();
            if (!"all".equals(cardListStr)) {
                for (String privateCard : privateCardList) {
                    noAccessCardMap.put(privateCard, privateCard);
                }
                if (StringUtils.isNotBlank(cardListStr)) {
                    String[] cardListArr = cardListStr.split(",");
                    for (String card : cardListArr) {
                        noAccessCardMap.remove(card);
                    }
                }
            }
        }
        String wxImg = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.aiCard.getModule(), "wxImg");
        String wxImgDesc = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.aiCard.getModule(), "wxImgDesc");
        String addGroupIcon = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.aiCard.getModule(), "addGroupIcon");
        response.setWxImg(wxImg);
        response.setWxImgDesc(wxImgDesc);
        response.setAddGroupIcon(addGroupIcon);

        String homeAdvice = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.aiCard.getModule(), "homeAdvice");
        response.setHomeAdvice(homeAdvice);
        String homeContentStr = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.aiCard.getModule(), "homeContent");
        Map<String,String> homeContentMap = JSON.parseObject(homeContentStr,Map.class);
        String homeContent = homeContentMap.get(uid);
        if (homeContent == null){
            homeContent = homeContentMap.get("default");
        }

        boolean showCard = ConfigUtil.getInstance().isShowCard(uid);
        if (!showCard){
            homeContent = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.aiCard.getModule(), "cardBlackListHint");
        }

        response.setHomeContent(homeContent);
        String cardListStr = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.aiCard.getModule(), "cardList");
        if (StringUtils.isNotBlank(cardListStr)){
            List<AiCardCategoryDto> cardCategoryList = JSON.parseArray(cardListStr,AiCardCategoryDto.class);
            if (CollectionUtils.isEmpty(cardCategoryList)){
                return response;
            }
            for (AiCardCategoryDto aiCardCategoryDto : cardCategoryList){
                List<AiCardDto> cardList = aiCardCategoryDto.getCardList();
                if (CollectionUtils.isEmpty(cardList)){
                    continue;
                }
                for (AiCardDto aiCardDto : cardList){
                    String optionType = noAccessCardMap.get(aiCardDto.getOptionType());
                    if (optionType != null){
                        aiCardDto.setIsLock(true);
                    }
                }
                cardList = cardList.stream()
                        //正序排序
                        .sorted(Comparator.comparing(AiCardDto::getId, Comparator.nullsLast(Long::compareTo)))
                        .collect(Collectors.toList());
                aiCardCategoryDto.setCardList(cardList);
            }
            cardCategoryList = cardCategoryList.stream()
                    //正序排序
                    .sorted(Comparator.comparing(AiCardCategoryDto::getId, Comparator.nullsLast(Long::compareTo)))
                    .collect(Collectors.toList());
            response.setCardCategoryList(cardCategoryList);
        }
        return response;
    }

    /**
     * 获取卡片示例
     * @return
     */
    public GetAiExampleResponse getAiExample(String optionType) {
        GetAiExampleResponse response = new GetAiExampleResponse();
        if (StringUtils.isBlank(optionType)){
            return response;
        }
        String config = ConfigUtil.getInstance().getConfig(ConfigModuleEnum.aiExample.getModule(), optionType);
        if (StringUtils.isBlank(config)){
            return response;
        }
        List<AiExampleDto> exampleList = JSON.parseArray(config,AiExampleDto.class);
        response.setExampleList(exampleList);
        return response;
    }
}
